<template>
  <div class="layout-container">
    <div class="header">
      <img src="/public/pictures/logo.jpg" class="header-logo">
      <h1>配电电缆故障风险评估与差异化巡检系统</h1>
      <button class="shutdown-button" @click="showShutdownModal"><i class="el-icon-switch-button"></i> 退出</button>
    </div>
    <div class="main-content">
      <div class="sidebar">
        <!--				<div class="user-info" @click="showUserDetails">-->
        <!--					<div><i class="el-icon-user"></i> 用户名: {{ username }}</div>-->
        <!--					<div><i class="el-icon-time"></i> 登录时间: {{ initialLoginTime }}</div>-->
        <!--					<div><i class="el-icon-watch"></i> 总时长: {{ loginDuration }}</div>-->
        <!--				</div>-->
        <div class="search-input-container">
          <input type="text" v-model="searchQuery" placeholder="搜索菜单..." class="menu-search-input">
          <i class="el-icon-search search-icon"></i>
        </div>
        <ul class="menu-list">
          <li v-for="item in filteredMenuItems" :key="item.name" class="menu-item"
              :class="{ 'has-children': item.children && item.children.length > 0, 'selected': item.selected || (item.children && item.children.some(child => child.selected)) }">
            <div class="menu-item-header" @click="toggleMenu(item)">
              <i :class="item.icon"></i>
              <span>{{ item.name }}</span>
              <span v-if="item.children && item.children.length > 0" class="toggle-icon">{{
                  item.expanded
                      ? '-' : '+'
                }}</span>
            </div>
            <ul v-if="item.children && item.children.length > 0" v-show="item.expanded"
                class="submenu-list">
              <li v-for="child in item.children" :key="child.name" class="submenu-item"
                  :class="{ 'selected': child.selected, 'unselected': !child.selected }"
                  @click.stop="selectMenuItem(child)">
                <i :class="child.icon"></i>
                <span>{{ child.name }}</span>
              </li>
            </ul>
          </li>
        </ul>
        <div class="sidebar-footer"></div>
      </div>
      <div class="content-area">
        <component v-if="currentComponent" :is="currentComponent"/>
      </div>
    </div>
  </div>
</template>

<style src="./Mainpage.css" scoped></style>

<script>
import DataImport from './DataImport.vue';
import CableLineDistribution from './CableLineDistribution.vue';
import CableSegmentDistribution from './CableSegmentDistribution.vue';
import RiskAssessmentDetails from './RiskAssessmentDetails.vue';
import RelationMap from "./RelationMap.vue";
import RelationMainpage from "./RelationMainpage.vue";
import { useRoute } from 'vue-router';


export default {
  name: 'Mainpage',
  components: {
    DataImport,
    CableLineDistribution,
    CableSegmentDistribution,
    RiskAssessmentDetails,
    RelationMap,
    RelationMainpage,
  },
  data() {
    return {
      username: '', // Default value
      currentTime: '',
      initialLoginTime: '', // Add initialLoginTime property
      loginDuration: '', // Add loginDuration property
      searchQuery: '', // Add searchQuery data property for menu search
      currentComponent: null,
      menuItems: [
        {
          name: '数据分析',
          icon: 'el-icon-folder',
          color: '#00914D',
          expanded: false,
          children: [
            {
              name: '电缆线路分布',
              icon: 'el-icon-s-home',
              color: '#00914D',
              component: 'RelationMainpage'
            }
          ]
        },
        {
          name: '数据管理',
          icon: 'el-icon-folder',
          color: '#00914D',
          expanded: false,
          children: [
            {
              name: '数据导入',
              icon: 'el-icon-s-home',
              color: '#00914D',
              component: 'DataImport'
            }
          ]
        }
      ]
    };
  },
  computed: {
    filteredMenuItems() {
      if (!this.searchQuery) {
        return this.menuItems;
      }
      const query = this.searchQuery.toLowerCase();
      return this.menuItems.filter(item => {
        const matchesItem = item.name.toLowerCase().includes(query);
        const matchesChild = item.children && item.children.some(child => child.name.toLowerCase().includes(query));
        return matchesItem || matchesChild;
      }).map(item => {
        // If the parent matches or any child matches, include the parent
        if (item.name.toLowerCase().includes(query)) {
          // If parent matches, include all children (or filter children if needed)
          return {...item, expanded: true}; // Expand parent if it matches
        } else if (item.children) {
          // If parent doesn't match, filter children
          const filteredChildren = item.children.filter(child => child.name.toLowerCase().includes(query));
          if (filteredChildren.length > 0) {
            return {...item, children: filteredChildren, expanded: true}; // Include parent with matching children and expand
          }
        }
        return null; // Exclude if neither parent nor children match
      }).filter(item => item !== null); // Remove null entries
    }
  },
  mounted() {
    const route = useRoute(); // 获取当前路由对象
    let query = route.query.page; // 获取 URL 中的 name 参数
    console.log(query)
    if (query==='RelationMap') {
      this.currentComponent = RelationMap;
    }else {
      this.currentComponent = RelationMainpage;
    }
    const storedUsername = localStorage.getItem('username');
    if (storedUsername) {
      this.username = storedUsername;
    }
    // Read login timestamp from localStorage
    const loginTimestamp = localStorage.getItem('loginTimestamp');
    if (loginTimestamp) {
      const loginDate = new Date(parseInt(loginTimestamp));
      const year = loginDate.getFullYear();
      const month = (loginDate.getMonth() + 1).toString().padStart(2, '0');
      const day = loginDate.getDate().toString().padStart(2, '0');
      const hours = loginDate.getHours().toString().padStart(2, '0');
      const minutes = loginDate.getMinutes().toString().padStart(2, '0');
      const seconds = loginDate.getSeconds().toString().padStart(2, '0');
      this.initialLoginTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      this.calculateLoginDuration(parseInt(loginTimestamp));
      this.calculateLoginDuration(parseInt(loginTimestamp));
    }
    this.updateTime();
    // Update time and login duration every second
    this.timer = setInterval(() => {
      this.updateTime();
      this.calculateLoginDuration(parseInt(localStorage.getItem('loginTimestamp')));
    }, 1000);
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
  methods: {
    updateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      this.calculateLoginDuration(parseInt(localStorage.getItem('loginTimestamp')));
    },
    calculateLoginDuration(loginTimestamp) {
      if (!loginTimestamp) return;
      const now = Date.now();
      const durationInSeconds = Math.floor((now - loginTimestamp) / 1000);
      const hours = Math.floor(durationInSeconds / 3600);
      const minutes = Math.floor((durationInSeconds % 3600) / 60);
      const seconds = durationInSeconds % 60;
      this.loginDuration = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    },
    toggleMenu(item) {
      window.history.replaceState({}, '', '/dashboard');
      this.menuItems.forEach(menuItem => {
        if (menuItem !== item) {
          menuItem.expanded = false;
        }
      });
      item.expanded = !item.expanded;
      this.menuItems.forEach(menuItem => {
        menuItem.selected = false;
      });
      item.selected = true;
    },
    showShutdownModal() {
      // 实现确认弹框逻辑
      if (confirm('确定要退出吗？')) {
        console.log('用户确认退出');
        // 在此处添加退出逻辑，例如清除用户数据或导航到登录页面
        localStorage.removeItem('username');
        window.location.href = '/login';
      } else {
        console.log('用户取消退出');
      }
    },
    selectMenuItem(child) {
      this.menuItems.forEach(menuItem => {
        menuItem.children.forEach(subItem => {
          subItem.selected = false;
        });
      });
      child.selected = true;
      this.currentComponent = child.component;
    }
  },
  showUserDetails() {
    // TODO: Implement logic to show user details
    console.log('User info clicked');
    // Example: You might open a modal or navigate to a user details page
  }
};
</script>

<style scoped>
.submenu-item.selected {
  background-color: #164421;
  /* 深色背景 */
}

.content-area {
  flex: 1;
  padding: 20px;
  /* Add padding to create space around the content */
  overflow-y: auto;
  overflow-x: auto;
  /* Allow vertical scrolling if content overflows */
}

.search-input-container {
  position: relative;
  margin: 1px;
}

.menu-search-input {
  width: 100%;
  padding: 8px 30px 8px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.search-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  cursor: pointer;
}

.menu-search-input::placeholder {
  color: #999;
  opacity: 1;
}

.menu-search-input:focus::placeholder {
  opacity: 0;
}
</style>
